package org.dromara.business.modules.message.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.business.modules.message.domain.BuMessage;
import org.dromara.business.modules.message.domain.bo.BuMessageBo;
import org.dromara.business.modules.message.domain.vo.BuMessageVo;
import org.dromara.business.modules.message.mapper.BuMessageMapper;
import org.dromara.business.modules.message.service.IBuMessageService;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

/**
 * 消息通知Service业务层处理
 *
 * @author ckk
 * @date 2025-10-23
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class BuMessageServiceImpl implements IBuMessageService {

    private final BuMessageMapper baseMapper;

    /**
     * 分页查询消息通知列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 消息通知分页列表
     */
    @Override
    public TableDataInfo<BuMessageVo> queryPageList(BuMessageBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<BuMessage> lqw = buildQueryWrapper(bo);
        Page<BuMessageVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    @Override
    public Boolean setRead(Long id) {
        return new LambdaUpdateChainWrapper<>(baseMapper)
            .eq(id != -1, BuMessage::getId, id)
            .eq(BuMessage::getReceiverId, LoginHelper.getUserId())
            .set(BuMessage::getIsRead, 1)
            .set(BuMessage::getReadTime, new Date())
            .update();
    }

    @Override
    public Long unReadCount() {
        return new LambdaQueryChainWrapper<>(baseMapper)
            .eq(BuMessage::getReceiverId, LoginHelper.getUserId())
            .eq(BuMessage::getIsRead, 0)
            .count();
    }

    private LambdaQueryWrapper<BuMessage> buildQueryWrapper(BuMessageBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BuMessage> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(BuMessage::getId);
        lqw.eq(StringUtils.isNotBlank(bo.getTitle()), BuMessage::getTitle, bo.getTitle());
        lqw.eq(BuMessage::getReceiverId, LoginHelper.getUserId());
        return lqw;
    }

}
